<template>
  <el-container>
    <el-header>
      <el-row>
        <el-col :span="20">
          <el-menu
            router
            mode="horizontal"
            @select="handleSelect">
            <el-menu-item index="00" route="/home">首页</el-menu-item>
            <MenuTree :data="menuList"></MenuTree>
          </el-menu>
        </el-col>
        <el-col :span="4" class="info">
          <el-button type="primary" size="small" @click="logout">退出</el-button>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <router-view />
    </el-main>
  </el-container>
</template>

<script>
import { mapActions } from 'vuex'
import MenuTree from '@/components/main/MenuTree'
import consts from '@/utils/consts'

export default {
  name: 'Main',
  components: {
    MenuTree
  },
  data() {
    return {
      webSocket: null,
      menuList: this.$util.getMenuList()
    }
  },
  methods: {
    ...mapActions(['Logout', 'CacheDict']),
    initWebSocket() {
      if (this.$util.isSupportWebSocket()) {
        this.webSocket = new WebSocket(process.env.VUE_APP_API_WS_BASE_URL + '/' + this.$util.getToken())
        this.webSocket.onopen = this.onopen
        this.webSocket.onmessage = this.onmessage
        this.webSocket.onclose = this.onclose
        this.webSocket.onerror = this.onerror
      } else {
        console.log('您的浏览器暂不支持ws')
      }
    },
    onopen() {
      console.log('ws连接打开')
    },
    onmessage(event) {
      if (!event.data) return
      const data = JSON.parse(event.data)
      if (consts.WEB_SOCKET_CODE_REFRESH_DICT === data.code) {
        this.CacheDict()
      } else if (consts.WEB_SOCKET_CODE_REFRESH_USER === data.code) {
      }
    },
    onclose() {
      console.log('ws连接关闭')
    },
    onerror(event) {
      console.log('ws连接异常', event)
    },
    handleSelect(key, keyPath) {
      console.log(key, keyPath)
    },
    logout() {
      this.Logout()
      this.$router.push('/login')
    }
  },
  created() {
    this.initWebSocket()
  },
  mounted() {
    this.CacheDict()
  },
  destroyed() {
    if (this.$util.isSupportWebSocket()) {
      this.webSocket.close()
    }
  }
}
</script>

<style lang="less" scoped>
  .info {
    height: 61px;
    line-height: 61px;
    text-align: right;
  }
</style>
